
<template>
  <Card :dis-hover="true">
    <p slot="title">{{budget.Name}}</p>
    <base-table :data="data" :columns="columns" @add="addHandler" 
    @update="updateHandler" @check="checkHandler" @approve="approveHandler"
    @delete="deleteHandler" ck></base-table>
     <Modal
        v-model="modelFlag"
        title="预算实际使用情况"
        @on-ok="ok"
        @on-cancel="cancel">
        <Form ref="formValidate" :model="formItem" :rules="ruleValidate" :label-width="80" label-position="left">
          <FormItem label="用途" prop="Name">
            <Input v-model="formItem.Name"></Input>
          </FormItem>
           <FormItem label="实际使用" prop="Used">
            <Input v-model="formItem.Used" number></Input>
          </FormItem>
          <FormItem label="说明" prop="Remark">
              <Input v-model="formItem.Remark" placeholder=""></Input>
          </FormItem>
        </Form>

    </Modal>
  </Card>
</template>

<script>
import moment from 'moment';
import BaseTable from '@c/table/table';
import { newApiParams } from '@/common/utils';
export default {
  name: 'ProjectBudgetUsed',
  components: {
    BaseTable
  },
  data () {
    return {
      modelFlag: false,
      isAdd: false,
      data: [],
      columns: [
        {
          title: '排序',
          type: 'index'
        },
        {
          title: '用途',
          key: 'Name'
        },
        {
          title: '实际使用',
          render: (h, { row }) => {
            return h('span', {}, `￥${row.Used}`);
          }
        },
        {
          title: '说明',
          key: 'Remark'
        }
      ],
      formItem: {
      },
      ruleValidate: {
        Name: [
          { required: true, message: '请输入用途', trigger: 'blur' }
        ],
        Used: [
          { required: true, type: 'number', message: '请输入实际使用金额', trigger: 'change' }
        ],
        Remark: [
          { required: true, message: '请输入用途说明', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    budget () {
      return this.$route.params.budget; 
    }
  },
  methods: {
    addHandler () {
      this.isAdd = true;
      this.modelFlag = true;
    },
    updateHandler () {},
    checkHandler (rows) {
      if (Array.isArray(rows) && rows.length === 1) {
        this.formItem = rows[0];
        this.isAdd = false;
        this.modelFlag = true;
      } else {
        this.$Message.warning('请选择一条数据操作！');
      }
    },
    approveHandler () {},
    deleteHandler (rows) {
      // DeleteImsUsedList
      if (Array.isArray(rows) && rows.length > 0) {
        this.$Modal.confirm({
          title: '操作确认',
          content: '删除后可能会影响其它功能使用，确认删除选中的数据吗？',
          onOk: () => {
            this.$api.DeleteImsUsedList(rows).then((res) => {
              this.$Message.success('操作成功！');
              this.getAll();
            }).catch((err) => {
              if (err) {
                this.$Message.error(err);
              }
            });
          }
        });
      } else {
        this.$Message.warning('请选择至少一条数据操作！');
      }
    },
    getAll () {
      let params = newApiParams();
      params.query.BudgetId = this.budget.Id;
      this.$api.QueryUsedByProject(params).then((res) => {
        if (Array.isArray(res.Data) && res.Data.length > 0) {
          this.data = res.Data;
        } else {
          this.data.length = 0;
        }
      }).catch((err) => {
        if (err) {
          this.$Message.error(err);
        }
      });
    },
    ok () {
      this.$refs['formValidate'].validate(valied => {
        if (valied) {
          // 计算当前预算项与实际使用情况
          let total = 0;
          for (let k = 0; k < this.data.length; k++) {
            total += this.data[k].Used;
          }
          total += this.formItem.Used;
          console.log('budget, used', this.budget.Budget, total);
          
          if (total > this.budget.Budget) {
            this.$Message.warning('超出预算!');
            return;
          }
          if (this.isAdd) {
            this.formItem.BudgetId = this.budget.Id;
            this.formItem.ProjectId = this.budget.ImsProject.Id;
            this.$api.CreateImsUsed(this.formItem).then((res) => {
              this.$Message.success('操作成功！');
              this.getAll();
              this.$refs['formValidate'].resetFields();
            }).catch((err) => {
              if (err) {
                this.$Message.error(err);
              }
            });
          } else {
            this.$api.UpdateImsUsed(this.formItem).then((res) => {
              this.$Message.success('操作成功！');
              this.getAll();
              this.$refs['formValidate'].resetFields();
            }).catch((err) => {
              if (err) {
                this.$Message.error(err);
              }
            });
          }
        } else {
          this.$Message.warning('请补充信息！');
        }
      });
    },
    cancel () {
      this.$refs['formValidate'].resetFields();
    }
  },
  mounted () {
    if (!this.budget) {
      this.$Message.warning('参数异常！');
      this.$router.push({ name: '已启动项目' });
    } else {
      this.getAll();
    }
  }
};
</script>

<style scoped>

</style>